package generatorGraphics.graphics;

import grammaticalClasses.nwConsole.ShowMote;
import grammaticalClasses.nwConsole.ShowStatCur;
import grammaticalClasses.nwConsole.ShowStatDay;
import grammaticalClasses.nwConsole.ShowStatShort;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import softwareControl.SearchCommands;

public class MoteLatency implements GraphInterface {
    
    private SearchCommands search;
    
    private String name;
    private String help;
    
    private ChartPanel chartPanel;
    private ArrayList<String> unitList;
    private ArrayList<ArrayList<String>> optionsList;
    private String unitActive;
    
    private ArrayList<Object> answer;
    private ArrayList<String> commands;
    
    public MoteLatency(){
        
        unitList = new ArrayList<>();
        optionsList = new ArrayList<>();
        
        name = "Mote Latency";
        help = "Help of Mote Latency";
        
        configUnitOptions();
        
        commands = new ArrayList<>();
        commands.add("ShowStatCur");
        commands.add("ShowStatShort");
        commands.add("ShowMote");
        commands.add("ShowStatDay");
        
        //createGraph("Erro-MoteLatency-Erro");
    }
    
    public void start(String directory){
        
        if(directory == null || directory.equals("")){
            search = new SearchCommands(commands);
        } else{
            search = new SearchCommands(directory, commands);
        }
        
        answer = (ArrayList<Object>) search.getCommandsAnswer();
        
    }
    
    /**
     * Configura todos os campos de unidades e de opções.
     * Realizando a ligação entre unidades e seus respectivos vetores de opções.
     */
    private void configUnitOptions(){

        // Adicionando as unidades
        unitList.add("Time Interval(15min)");
        unitList.add("Generic");
        unitList.add("Days");
        
        //Adicionando as opções
        //--Não existe definição de Opções
    }
        
    private void createGraph(String unit) {
        
        int indice;
        
//        if(search == null){
//            search = new SearchCommands(commands);
//            answer = (ArrayList<Object>) search.getCommandsAnswer();
//        }
        
        switch (unit){
            case "Time Interval(15min)":
                
                indice = search.getAnswer(commands, "ShowStatShort");
                
                chartPanel = new ChartPanel(buildGraphTimeInterval((ArrayList<ShowStatShort>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Generic":
                
                indice = search.getAnswer(commands, "ShowMote");
                
                chartPanel = new ChartPanel(buildGraphGeneric((ArrayList<ShowMote>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Days":

                indice = search.getAnswer(commands, "ShowStatDay");
                
                chartPanel = new ChartPanel(buildGraphDays((ArrayList<ShowStatDay>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350));
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            default:
                chartPanel = new ChartPanel(null);
                
                break;
        }
    }    
    
    private JFreeChart buildGraphTimeInterval(ArrayList<ShowStatShort> auxShort){
    
        ArrayList<TimeSeries> timeSeriesList = new ArrayList<>();
        for(int j=0; j<auxShort.get(0).getMoteStats().size(); j++){
            TimeSeries timeSeries = new TimeSeries(auxShort.get(0).getMoteStats().get(j).getId());
            timeSeriesList.add(timeSeries);
        }

        for(int i=0; i<timeSeriesList.size(); i++){
            for(int k=0; k<auxShort.size(); k++){
                for(int j=0; j<auxShort.get(k).getMoteStats().size(); j++){
                    if(timeSeriesList.get(i).getKey().equals(auxShort.get(k).getMoteStats().get(j).getId())){
                        String[] aux1 = (auxShort.get(k).getHourFinal()).split(":");
                        String[] aux2 = (auxShort.get(k).getDataFinal()).split("/");
                        aux2[2] = "20" + aux2[2];

                        try{
                            if((isNumber(aux1[2])) &&
                                (isNumber(aux1[1])) &&
                                (isNumber(aux1[0])) &&
                                (isNumber(aux2[2])) &&
                                (isNumber(aux2[1])) &&
                                (isNumber(aux2[0]))){

                                timeSeriesList.get(i).add(new Second(
                                    Integer.valueOf(aux1[2]), 
                                    Integer.valueOf(aux1[1]), 
                                    Integer.valueOf(aux1[0]), 
                                    Integer.valueOf(aux2[1]), 
                                    Integer.valueOf(aux2[0]), 
                                    Integer.valueOf(aux2[2])), 
                                    auxShort.get(k).getMoteStats().get(j).getLate());
                            }
                        } catch(SeriesException ex){
                            System.out.println("[Erro-MoteLatency] " + ex.toString());
                        }
                    }
                }
            }
        }

        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
        for(int i=0; i<timeSeriesList.size(); i++){
            timeseriescollection.addSeries(timeSeriesList.get(i));
        }

        JFreeChart chart = ChartFactory.createTimeSeriesChart(name, "Time Interval(15min)", 
                "Seconds", timeseriescollection, true, true, false);
        chart.setBackgroundPaint(new Color(238, 238, 238));

        XYPlot xyplot = (XYPlot) chart.getPlot();
        //xyplot.setInsets(new RectangleInsets(0.0D, 0.0D, 0.0D, 20D));
        //ValueMarker valuemarker = new ValueMarker(700D);
        //valuemarker.setPaint(Color.blue);
        //valuemarker.setAlpha(0.8F);
        //xyplot.addRangeMarker(valuemarker);
        xyplot.setBackgroundPaint(null);
        //xyplot.setBackgroundImage(JFreeChart.INFO.getLogo());
        //xyplot.getDomainAxis().setLowerMargin(0.0D);
        xyplot.getDomainAxis().setVerticalTickLabels(true);
        
        return chart;
        
    }
    
    private JFreeChart buildGraphGeneric(ArrayList<ShowMote> auxMote){
    
        DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
        for(int i=0; i< auxMote.size(); i++){
            dataset2.addValue(auxMote.get(i).getLate(),
                "Devices", 
                auxMote.get(i).getIdMote());
        }

        JFreeChart chart2 = ChartFactory.createBarChart(name, 
                "", "Seconds", 
                dataset2, PlotOrientation.VERTICAL, 
                true, true, false);
        chart2.setBackgroundPaint(new Color(238, 238, 238));

        CategoryPlot plot2 = (CategoryPlot) chart2.getPlot();
        plot2.setBackgroundPaint(Color.white);
        plot2.setDomainGridlinePaint(Color.white);
        plot2.setDomainGridlinesVisible(true);
        plot2.setRangeGridlinePaint(Color.white);

        return chart2;
        
    }
    
    private JFreeChart buildGraphDays(ArrayList<ShowStatDay> auxDay){
    
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for(int k=0; k<auxDay.size(); k++){
            for(int j=0; j<auxDay.get(k).getMoteStats().size(); j++){
                dataset.addValue(auxDay.get(k).getMoteStats().get(j).getLate(),
                    "Day " + auxDay.get(k).getidDay(),
                    auxDay.get(k).getMoteStats().get(j).getId());
            }
        }

        JFreeChart chart3 = ChartFactory.createBarChart(name, 
                "Devices",
                "Seconds",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);
        chart3.setBackgroundPaint(new Color(238, 238, 238));

        CategoryPlot plot = (CategoryPlot) chart3.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);
        
        return chart3;
        
    }
    
    /**
     * Verifica se o 'texto' é um número. Podendo ser inteiro ou float.
     * @param texto
     * @return 
     */
    public static boolean isNumber(String texto) {  
        if(texto == null) {
            return false;
        }  
        for (char letra : texto.toCharArray()) {
            if((letra < '0' || letra > '9') && (letra != '.')) {
                return false;
            }
        }  
        return true;  
        
    }
    
    @Override
    public String toString(){
        return name;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public ArrayList<String> getUnitList() {
        return unitList;
    }

    /**
     * Retorna o chartPanel 'default'
     * @return 
     */
    @Override
    public ChartPanel getChartPanel() {
        if(search != null){
            return chartPanel;
        } else {
            return new ChartPanel(null);
        }
    }

    @Override
    public String getHelp() {
        return help;
    }

    @Override
    public ChartPanel getChartPanel(String unit) {
        
        if(search != null){
            for(int i=0; i<unitList.size(); i++){
                if(unit.equals(unitList.get(i))){
                    createGraph(unit);
                }
            }
            return chartPanel;
        } else {
            return new ChartPanel(null);
        }   
    }

    @Override
    public ArrayList<String> getOptionsList(String unit) {
        ArrayList<String> auxReturn = new ArrayList<>();
        
        for(int i=0; i<optionsList.size(); i++){
            if((optionsList.get(i)).get(0).equals("[UNIT]" + unit)){
                
                for(int j=1; j<optionsList.size(); j++){
                    auxReturn.add(optionsList.get(i).get(j));
                }
            }
        }
        return auxReturn;
    }
    
}
